package com.beck.bee.dao;

import org.apache.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.mybatis.spring.SqlSessionTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * Created by sakawijaya on 3/29/2017.
 */
public abstract class BaseDaoImpl<T> implements BaseDao<T> {

    protected Logger logger = (Logger) LogManager.getLogger(getClass());

    /*分页查询sql id标识 --结果集*/
    private static final String SELECT_ENTRY_BY_WHERE_PAGE = "selectEntryByWherePage";
    /*分页查询sql id标识 --总数*/
    private static final String SELECT_ENTRY_BY_WHERE_COUNT = "selectEntryByWhereCount";

    /*按条件查询结果为list的sql id标识*/
    private static final String SELECT_ENTRY_BY_WHERE = "selectEntryByWhere";
    /*按主键查询sql id标识*/
    protected static final String SELECT_ENTRY_BY_KEY = "selectEntryByKey";
    /*按主键更新sql id标识*/
    protected static final String UPDATE_ENTRY_BY_KEY = "updateEntryByKey";
    /*按数组批量删除sql id标识*/
    private static final String DELETE_ENTRY_BY_ARRAY_KEYS = "deleteEntryByArrayKeys";
    /*按数组批量删除sql id标识*/
    private static final String DELETE_ENTRY_BY_KEY = "deleteEntryByKey";
    /*插入sql id标识*/
    protected static final String INSERT_ENTRY = "insertEntry";

    protected String getStatement(String statement) {
        return org.apache.commons.lang.StringUtils.join(new String[]{getNameSpace(), statement}, ".");
    }

    @Override
    public abstract String getNameSpace();
    
    @Resource
    protected SqlSessionTemplate sqlSessionTemplate;

    @Override
    public long insert(T t) {
        return sqlSessionTemplate.insert(getStatement(INSERT_ENTRY), t);
    }

    @Override
    public int delete(int... key) {
        return sqlSessionTemplate.delete(getStatement(DELETE_ENTRY_BY_ARRAY_KEYS), key);
    }

    @Override
    public int delete(Serializable key) {
        return sqlSessionTemplate.delete(getStatement(DELETE_ENTRY_BY_KEY), key);
    }

    @Override
    public int delete(T t){
        return 0;
    }

    @Override
    public int update(T t) {
        return sqlSessionTemplate.update(getStatement(UPDATE_ENTRY_BY_KEY), t);
    }

    @Override
    public T select(Serializable key) {
        return sqlSessionTemplate.selectOne(getStatement(SELECT_ENTRY_BY_KEY), key);
    }

    @Override
    public List<T> select(T t) {
        return sqlSessionTemplate.selectList(getStatement(SELECT_ENTRY_BY_WHERE), t);
    }

    @Override
    public int selectCount(T t) {
        return (Integer) sqlSessionTemplate.selectOne(getStatement(SELECT_ENTRY_BY_WHERE_COUNT), t);
    }

    @Override
    public List<T> selectPage(T t) {
        return sqlSessionTemplate.selectList(getStatement(SELECT_ENTRY_BY_WHERE_PAGE), t);
    }

}
